import axios, {AxiosRequestConfig} from 'axios';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;

export default function useRequest() {
    const get = async (url: string, config?: AxiosRequestConfig) => {
        try {
            const response = await axios.get(url, config);
            return response.data;
        } catch (error: any) {
            throw new Error(error.response.data.message || error.message || '请求失败');
        }
    };

    const post = async (url: string, data?: any, config?: AxiosRequestConfig) => {
        try {
            const response = await axios.post(url, data, config);
            return response.data;
        } catch (error: any) {
            throw new Error(error.response.data.message || error.message || '请求失败');
        }
    };

    const put = async (url: string, data?: any, config?: AxiosRequestConfig) => {
        try {
            const response = await axios.put(url, data, config);
            return response.data;
        } catch (error: any) {
            throw new Error(error.response.data.message || error.message || '请求失败');
        }
    };

    const deleteRequest = async (url: string, config?: AxiosRequestConfig) => {
        try {
            const response = await axios.delete(url, config);
            return response.data;
        } catch (error: any) {
            throw new Error(error.response.data.message || error.message || '请求失败');
        }
    };

    return {
        get,
        post,
        put,
        deleteRequest,
    }
}
